﻿using System;
using System.Collections.Generic;
using SystemX.Cache;

namespace SystemX.Web.Cache
{
	public class WebCache:CacheBase
	{
		/// <summary>
		/// web application cache
		/// </summary>
		protected static System.Web.Caching.Cache NetCache {
			get
			{
				if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Cache != null)
					return System.Web.HttpContext.Current.Cache;

				return System.Web.HttpRuntime.Cache;
			}
		}
		public override void Add(string key, object item, DateTime absoluteExpiration, TimeSpan slidingExpiration)
		{
			var cachedItem = new CachedItem(key, item, absoluteExpiration, slidingExpiration);
			var cachedKey=String.Format("{0}|{1}", context, key);
			if (absoluteExpiration != Cacher.NoAbsoluteExpiration)
			{
				NetCache.Add(
					cachedKey,
					cachedItem,
					null,
					absoluteExpiration,
					System.Web.Caching.Cache.NoSlidingExpiration,
					System.Web.Caching.CacheItemPriority.Default,
					null
					);

			}
			else { 
				NetCache.Add(cachedKey,
					item,
					null,
					System.Web.Caching.Cache.NoAbsoluteExpiration,
					slidingExpiration,
					System.Web.Caching.CacheItemPriority.Default,
					null
					);
			}
		}

		public override bool Exists(string key)
		{
			var cachedKey = String.Format("{0}|{1}", context, key);
			return NetCache[cachedKey] != null;
		}

		public override object Get(string key)
		{
			var cachedKey = String.Format("{0}|{1}", context, key);
			var item =NetCache.Get(cachedKey) as CachedItem;
			if (item != null) return item.Item;
			return null;
		}

		protected override CachedItem GetCachedItem(string key)
		{
			var cachedKey = String.Format("{0}|{1}", context, key);
			var item = NetCache.Get(cachedKey) as CachedItem;
			return item;
		}

		protected override void Purge()
		{
			//do nothing
		}

		public override void Remove(string key)
		{
			var cachedKey = String.Format("{0}|{1}", context, key);
			NetCache.Remove(cachedKey);
		}

		public override void Update(string key, object item)
		{
			var cachedKey = String.Format("{0}|{1}", context, key);
			NetCache[cachedKey] = item;
		}

		public override System.Collections.IEnumerator GetEnumerator()
		{
			var keys = new List<string>();
			var enu = NetCache.GetEnumerator();
			while (enu.MoveNext()) {
				if (enu.Key.ToString().StartsWith(context)) {
					keys.Add(enu.Key.ToString());
				}
			}
			return keys.GetEnumerator();
		}
	}
}
